package com.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


/*
      1、上传文件设置enctype为multipart/form-data,
      2、一次选择多个文件加属性multiple="multiple"(name和value一致时，value可省略),后端使用MultipartFile[]数组接收

      <form method="post" action="/upload" enctype="multipart/form-data">
          <input type="file" name="files" id="files" multiple><br/><br/>
          <input type="submit" value="Submit">
      </form>
 */


/**
 * 使用form upload file
 */
@Controller
public class UploadController {

    //Save the uploaded file to this folder
    @Value("${file.root.path}")
    private String uploadFolder;

    @GetMapping("/")
    public String index(){
        return "upload";
    }

    @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("files") MultipartFile[] files, RedirectAttributes redirectAttributes){
        StringBuilder sb = new StringBuilder();
        sb.append("you successfully uploaded ");
        if(files.length==0){
            redirectAttributes.addFlashAttribute("messsage","Please select a file to upload");
            return "redirect:uploadStatus";
        }
        //get the file and save it somewhere
        byte[] bytes;
        try {
            Path dir = Paths.get(uploadFolder);
            if(!Files.exists(dir)){
                Files.createDirectories(dir);
            }

            for (MultipartFile file : files) {
                //保存文件方式一
                /*bytes = file.getBytes();
                Path path = Paths.get(uploadFolder + file.getOriginalFilename());
                Files.write(path,bytes);*/

                //保存文件方式二
                file.transferTo(new File(uploadFolder + file.getOriginalFilename()));
                sb.append("`").append(file.getOriginalFilename()).append("`");
            }
            redirectAttributes.addFlashAttribute("message",sb);
        } catch (IOException e) {
            redirectAttributes.addFlashAttribute("message","Server throw IOException");
            e.printStackTrace();
        }
        return "redirect:uploadStatus";
    }

    @GetMapping("/uploadStatus")
    public String uploadStatus(){
        return "uploadStatus";
    }

}


/*
      uploadStatus.html

      <div th:if="${message}">
          <h2 th:text="${message}"></h2>
      </div>
 */